package com.problem.leetcode;

import org.openjdk.jmh.annotations.*;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * @author didi
 * @DESCRIPTION
 * @create 2019-05-28 11:06
 **/
@State(Scope.Thread)
@BenchmarkMode({Mode.Throughput})
@Warmup(iterations = 3, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.MICROSECONDS)
@Threads(16)
@Fork(4)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class Problem557 {

    public String reverseWords(String s) {
        List<String> strs         = findStringArray(s, ' ');
        StringJoiner stringJoiner = new StringJoiner(" ");
        for (int index = 0; index < strs.size(); index++) {
            stringJoiner.add(reverseString(strs.get(index)));
        }
        return stringJoiner.toString();
    }

    private List<String> findStringArray(String s, char ch) {
        StringBuilder stringBuilder = new StringBuilder();
        List<String>  list          = new ArrayList<>();
        for (int index = 0; index < s.length(); index++) {
            if (s.charAt(index) != ch) {
                stringBuilder.append(s.charAt(index));
            } else {
                list.add(stringBuilder.toString());
                stringBuilder.delete(0, stringBuilder.length());
            }
        }
        //处理最后一个字符串
        if (stringBuilder.length() > 0) {
            list.add(stringBuilder.toString());
        }

        return list;
    }


    @Benchmark
    public void testreverseWords() {
        String s = "Let's take LeetCode contest";
        reverseWords(s);
    }


    public String reverseString(String s) {
        if (s == null) {
            return null;
        }
        char[] values = s.toCharArray();
        int    begin  = 0, end = s.length() - 1;
        while (begin < end) {
            swap(values, begin, end);
            ++begin;
            --end;
        }
        return String.valueOf(values);
    }

    public void swap(char[] strs, int begin, int end) {
        char tmp = strs[begin];
        strs[begin] = strs[end];
        strs[end] = tmp;
    }

}
